//	按时间分类。时间轴为时间。具体分为历史平均，2012等。这是一个map的key
//	x轴为地区列表。每个key对应一组数据，[地区的年平均时间]，点击出现地区的12个月平均时间
//	我拿到的应该是 各个地区的各个动作。先分成地区map。每个地区map遍历得出地区各时间。有一个按照月份分类的map。有一个按照年份分类的map
var protectInitData = [];
var areas = [];
//	年份map key为年份   value为[所有的动作]
var yearProtectMap = new Map();
//  年份map key为年份  value为{'1月':[所有的动作],'2月':[所有的动作]}
var monthProtectMap = new Map();
//	地域map key为地域  value为 [所有的动作]   
var areaProtectMap = new Map();
var years = [];
var months = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'];
var maxLag = 0;
var minLag = 10000;
//	key是年份，value是[[area,20],[area,30],[area,40]]
//var protectChart3Data = new Map();
//	属性名是各个公司，各个属性的值是 map。map里key是年份，value是[['1月',20],['2月',25],['',45]]
//	对于年份：历史总计，value是[['2012年',12],[],[],[]]
var protectChart4Data = {};
//	key为year value{['1月',max,ave],['2月',max,ave]} 若为历史总计 {['2012年',max,ave],[]} 
var selectedArea = "";
var selectedYearIndex = 0;

var ProtectChart3 = null;
var ProtectChart4 = null;
var ProtectChart5 = null;
var year;
var protect = null;

var yearsData = [];
var areaLags = [];
var startYear;
var endYear;
var protectYearData = [];
var fixedChart5Data = new Map();
var fixedChart3Data = new Map();

$(function() {
	initYear();
	initProtectInitData();
	var t1 = window.setInterval(function() {
		var w = $('#protectChart5').width() + "";
		if (w != '0') {
			protect = new initProtect();
			window.clearInterval(t1);
		}
	}, 20);
	onYearChanged();
});

$(window).resize(function() {
	protect.resizeChart();
});

function initYear() {
	var date = new Date();
	var currentYear = date.getFullYear();
	$("#startYear").val(currentYear);
	$("#startYear").datetimepicker({
		startView:4,
		minView:4,
		autoclose:true,
		format:'yyyy'
	});
	$("#endYear").val(currentYear);
	$("#endYear").datetimepicker({
		startView:4,
		minView:4,
		autoclose:true,
		format:'yyyy'
	});
}
function initProtectInitData(){
	$.ajaxSettings.async = false;
	$.getJSON("/rest/protectAction/getProtectActionAll", function(result) {
		protectInitData=result;
	});
	$.getJSON("/rest/protectAction/getProtectActionYearData", function(result) {
		protectYearData=result;
	});
	$.ajaxSettings.async = true;
}

function initProtect(){
	protectInitData.sort(compare);
	initProtectMap(protectInitData);
	this.resizeChart = function(){
		ProtectChart5.resize();
		ProtectChart4.resize();
		protect.resize();
	};
}

function compare(obj1,obj2){
	if(obj1[1]<obj2[1]){
		return -1;
	}else{
		return 1;
	}
}

function initProtectMap(protectInitData){
	for(var i in protectInitData) {
		var protect = protectInitData[i];
		initYearProtectMap(protect);
		initMonthProtectMap(protect);
		initAreaProtectMap(protect);
	}
	years = yearProtectMap.keys;
	years.unshift(0);
	years.sort();
	initFixedProtectChart5Data();
	initFixedProtectChart3Data();
	onYearChanged();
}

function onYearChanged() {
	startYear = $("#startYear").val();
	endYear = $("#endYear").val();
	var sy = Number(startYear);
	var ey = Number(endYear);
	var flag = false;
	if(sy == ey) {
		for(var i in years) {
			if(sy == years[i]) {
				flag = true;
				selectedYearIndex = i;
				initYearDataChart5();
				initProtectChart5();
				initYearDataChart3();
				initProtectChart3();
				initProtectChart4Data();
			}
		} 
		if(false == flag) {
			$("#protectChart5").html("该时间暂无数据信息");
			$("#protectChart4").html("该时间暂无数据信息");
			$("#protectChart3").html("该时间暂无数据信息");
		}
	} else {
		years.splice(0,1,sy+"~"+ey);
		selectedYearIndex = 0;
		initYearDataChart5();
		initProtectChart5();
		initYearDataChart3();
		initProtectChart3();
		initProtectChart4Data();
	}
}

function initYearProtectMap(protect) {
	var year = protect[1];
	var yearvalue = yearProtectMap.get(year);
	if(!yearvalue){
		yearvalue = [];
		yearProtectMap.put(year,yearvalue);
	}
	yearvalue.push(protect);
}

function initMonthProtectMap(protect) {
	var year = protect[1];
	var month = protect[2];
	var monthvalue = monthProtectMap.get(year);
	if(!monthvalue){
		monthvalue = {'1月':[],'2月':[],'3月':[],'4月':[],'5月':[],'6月':[],'7月':[],'8月':[],'9月':[],'10月':[],'11月':[],'12月':[]};
		monthProtectMap.put(year,monthvalue);
	}
	monthvalue[month+"月"].push(protect);
}

function initAreaProtectMap(protect) {
	var area = protect[0];
	var areavalue = areaProtectMap.get(area);
	if(!areavalue){
		areavalue = [];
		areaProtectMap.put(area, areavalue);
	}
	areavalue.push(protect);
	if(areas.indexOf(area) == -1){
		areas.push(area);
		protectChart4Data[area] = new Map();
	}
}

function initProtectChart4Data() {
	var area=0;
	console.log(protectChart4Data);
	for(area in protectChart4Data){
		//每个地域的map:key为年份，value为[['1月',25],['2月',20]]
		var yearMonthValueMap = protectChart4Data[area];
		var yearMonthProtectMap = new Map();
		var protects = areaProtectMap.get(area);
		var j=0;
		for(j in years){
			yearMonthValueMap.put(years[j],[]);
			yearMonthProtectMap.put(years[j],{
				'1月':[],
				'2月':[],
				'3月':[],
				'4月':[],
				'5月':[],
				'6月':[],
				'7月':[],
				'8月':[],
				'9月':[],
				'10月':[],
				'11月':[],
				'12月':[]
			});
		}
		j=0;
		for(j in protects){
			var protect = protects[j];
			var year = protect[1];
			var month = protect[2];
			if(null != month) {
				var lag = protect[3];
				yearMonthProtectMap.get(year)[month+"月"].push(lag);
			}
		}
		for(j=1;j<years.length;j++){
			var year = years[j];
			var monthAves = yearMonthValueMap.get(year);
			var monthProtects = yearMonthProtectMap.get(year);
			for(var month in monthProtects){
				var mprotects =  monthProtects[month];
				var i=0;
				var sum = 0;
				var num = 0;
				for(i in mprotects){
					sum = sum + mprotects[i];
					num++;
				}
				num = num == 0? 1:num;
				monthAves.push([month,(sum/num).toFixed(2)]);
			}
		}
		//添加各个年份的历史总计
		//历史总计：[[2012年,3],[],[]]
		for(i=1;i<years.length;i++){
			var sum = 0;
			var num = 0;
			for(j=0;j< months.length;j++){
				//[[1月，20],[],[]]
				var monthAves = yearMonthValueMap.get(years[i]);
				var value = Number(monthAves[j][1]);
				sum = sum + value;
				if(value!=0){
					num++;
				}
			}
			if(num == 0){
				num = 1;
			}
			yearMonthValueMap.get(years[0]).push([years[i],(sum/num).toFixed(2)]);
		}
	}
	console.log("protectChart4Data:");
	console.log(protectChart4Data);
	initProtectChart4();
}

/**
 * 根据选择查看的年份动态修改areaLags[]，protectChart3Data.put(years[0], areaLags);
 * @returns
 */
function initYearDataChart3() {
	areaLags = [];
	var valueMap = new Map();
	var i = 0;
	for(i in areas) {
		valueMap.put(areas[i], [0,0]);
	}
	i=0;
	for(i in protectInitData) {
		var area = protectInitData[i][0];
		var lag = Number(protectInitData[i][3]);//均值
		var sum = Number(valueMap.get(area)[0]);
		var num = valueMap.get(area)[1];
		valueMap.put(area,[sum+lag,num+1]);
	}
	i=0;
	for(i in areas) {
		var area =areas[i];
		var sum = valueMap.get(area)[0];
		var num = valueMap.get(area)[1] == 0? 1:valueMap.get(area)[1];
		areaLags.push([area,(sum/num).toFixed(2)]);
	}
}
/**
 * 每个年份的数据是固定的，仅第一次进入页面的时候调用。
 * @returns
 */
function initFixedProtectChart3Data() {
	//各个年份
	for(var j=1;j < years.length;j++){
		var areaLags = [];
		var yearsdata = yearProtectMap.get(years[j]);
		var valueMap = new Map();
		i = 0;
		for(i in areas){
			valueMap.put(areas[i], [0,0]);
		}
		i=0;
		for(i in yearsdata){
			var area = yearsdata[i][0];
			var lag = Number(yearsdata[i][3]);
			var sum = Number(valueMap.get(area)[0]);
			var num = Number(valueMap.get(area)[1]);
			valueMap.put(area,[sum+lag,num+1]);
		}
		i=0;
		for(i in areas){
			var sum = Number(valueMap.get(areas[i])[0]);
			var num = Number(valueMap.get(areas[i])[1] == 0? 1:valueMap.get(areas[i])[1]);
			if(areas[i] != null){
				areaLags.push([areas[i],(sum/num).toFixed(2)]);
			}
		}
		fixedChart3Data.put(years[j], areaLags);
	}
}

/**
 * 每个年份的数据是固定的，仅第一次进入页面的时候调用。
 * @returns
 */
function initProtectChart3() {
	var protectChart3Data = fixedChart3Data;
	protectChart3Data.put(years[0], areaLags);
	var bar = new TimeBar('protectChart3');
	startYear = $("#startYear").val();
	endYear = $("#endYear").val();
	var sy = Number(startYear);
	var ey = Number(endYear);
	if(sy == ey) {
		year = sy;
	} else {
		year = sy+"~"+ey;
	}
	for(var i in areas){
		if(areas[i] == null){
			areas.splice(i,1);
		}
	}
	bar.setxAxis(areas);
	bar.setxAxisTitle("公司");
	bar.setyAxisTitle("ms");
	bar.setTimePoint(year);
	bar.setTimePointTitle(year+"年各单位保护平均动作时间");
	bar.setSubTitle("点击可查看该单位该年保护动作时间详细信息");
	bar.setTitlePosition('center');
	var yaxis = [];
	var j=0;
	var yaxisData = protectChart3Data.get(year);
	for(j in yaxisData){
		yaxis.push(yaxisData[j][1]);
	}
	bar.setTimePointyAxis(yaxis);
	bar.setTimePointyAxisName("保护平均动作时间");
	bar.setSelectedIndex(selectedYearIndex);
	bar.setZoomTool(false);
	var option = bar.getOption();
	option.baseOption.timeline.show = false;
	option.baseOption.title.textStyle.fontWeight = "normal";
	option.baseOption.title.textStyle.fontSize =16;
	option.baseOption.legend.show = false;
	bar.setTitlePosition('center');
	bar.show();

	selectedArea = areas[0];
	bar.getChart().on('click',function(params){
		if(areas.indexOf(params.name) != -1){
			selectedArea = params.name;
			initProtectChart4();
		}
	});
	ProtectChart3 = bar.getChart();
	return ProtectChart3;
}

function initProtectChart4() {
	var data = protectChart4Data[selectedArea];
	var line = new TimeLineChart('protectChart4');
	line.setyAxisTitle("ms");
	var i=0;
	for(i=0;i< years.length;i++){
		var year = years[i];
		line.setTimePoint(year);
		line.setTimePointTitle(selectedArea+year+"年保护平均动作时间");
		var yaxis = [];
		var j=0;
		var yaxisData = data.get(year);
		for(j in yaxisData){
			yaxis.push(yaxisData[j][1]);
		}
		line.setTimePointyAxis(yaxis);
		line.setTimePointyAxisName("保护平均动作时间");
		if(i == 0){
			line.setTimePointxAxis(years.slice(1));
			line.setTimePointxAxisTitle("年份");
		}else{
			line.setTimePointxAxis(months);
			line.setTimePointxAxisTitle("月份");
		}
	}
	line.setSelectedIndex(selectedYearIndex);
	line.setZoomTool(false);
	var option = line.getOption();
	option.baseOption.timeline.show = false;
	option.baseOption.title.right = "center";
	option.baseOption.title.textStyle.fontWeight = "normal";
	option.baseOption.title.textStyle.fontSize = 16;
	option.baseOption.legend.show = false;
	line.show();

	ProtectChart4 = line.getChart();
	return ProtectChart4;
}

/**
 * 根据选择查看的年份动态修改yearsData数据，protectChart5Data.put(years[0],yearsData);
 * @returns
 */
function initYearDataChart5() {
	var map = new Map();
	for(var y = startYear;y<=endYear;y++) {
		map.put(y,[]);
	}
	for(var i in protectYearData) {
		var protect = protectYearData[i];
		var year = protect[1];
		var yearValue = map.get(year);
		if(typeof(yearValue) != "undefined") {
			yearValue.push(protect);
		}
	}
	yearsData = [];
	for(var y = startYear;y<=endYear;y++){
		var yearMax = 0;
		var yearSum = 0;
		var yearNum = 0;
		var yearProtects = map.get(y);
		if(yearProtects.length>0) {
			for(var z=0;z<yearProtects.length;z++){
				var protect = yearProtects[z];
				var avgActTime = 0.00;
				var maxActTime = 0;
				if(protect) {
					avgActTime = Number(protect[3]);
					maxActTime = Number(protect[4]);
					if(maxActTime > yearMax){
						yearMax = maxActTime;
					}
					yearNum++;
					yearSum = yearSum + avgActTime;
				} 
			}
			yearsData.push([y,yearMax,(yearSum/yearNum).toFixed(2)]);
		} else {
			yearsData.push([y,0,0.00]);
		}
	}
}

function initProtectChart5() {
	var protectChart5Data = fixedChart5Data;
	protectChart5Data.put(years[0],yearsData);
	var line = new TimeLineChart('protectChart5');
	var i=0;
	for(i=0;i<years.length;i++ ){
		var year = years[i];
		var yearData = protectChart5Data.get(year);
		var maxList = [];
		var aveList = [];
		var xList = [];
		var j=0;
		for(j=0;j<yearData.length;j++){
			var data = yearData[j];
			xList.push(data[0]);
			maxList.push(data[1]);
			aveList.push(data[2]);
		}
		line.setTimePoint(year).setTimePointTitle(year+"年500kv系统主保护动作时间")
		.setTimePointxAxis(xList)
		.setTimePointyAxis(maxList).setTimePointyAxisName("保护最长动作时间").setyAxisTitle("ms")
		.setTimePointyAxis(aveList).setTimePointyAxisName("保护平均动作时间")
		.setSelectedIndex(selectedYearIndex);
		
		line.getOption().baseOption.timeline.show = false;
		var options = line.getOption().options;
		var option = options[options.length-1];
		line.getOption().baseOption.grid.bottom=40;
		line.getOption().baseOption.grid.top=70;
		option.legend.top = 30;
		option.title.right = "center";
		option.title.textStyle.fontWeight = "normal";
		option.title.textStyle.fontSize = 16;
	}
	line.setZoomTool(false).setRestore(false).setMagicType(false);
	line.show();
	ProtectChart5  = line.getChart();
	return ProtectChart5;
}

/**
 * 每个年份的数据是固定的，仅第一次进入页面的时候调用。
 * @returns
 */
function initFixedProtectChart5Data(){
	for(var i=1;i<years.length;i++){
		year = years[i];
		var yearProtects = monthProtectMap.get(year);
		var yearData = [];
		fixedChart5Data.put(year, yearData);
		var j="";
		for(j in yearProtects){
			var month = j;
			var monthMax = 0;
			var monthSum = 0;
			var monthNum = 0;
			var monthProtects = yearProtects[month];
			if(monthProtects.length>0){
				var z=0;
				for(z=0;z<monthProtects.length;z++){
					var protect = monthProtects[z];
					var avgActTime = 0.00;
					var maxActTime = 0;
					if(protect) {
						avgActTime = Number(protect[3]);
						maxActTime = Number(protect[4]);
						if(maxActTime > monthMax){
							monthMax = maxActTime;
						}
						monthNum++;
						monthSum = monthSum + avgActTime;
					} 
				}
				yearData.push([month,monthMax,(monthSum/monthNum).toFixed(2)]);
			} else {
				yearData.push([month,0,0.00]);
			}
		}
	}
}